//
//  BanBu_SendMsg.m
// Halfarea
//
//  Created by Wang Xj on 14-1-22.
//
//

#import "BanBu_SendMsg.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_ChatCellAPI.h"
#import "BanBu_ChatViewController.h"
#import "CJSONSerializer.h"
#import "BanBu_VIPAlert.h"

@implementation BanBu_SendMsg
static BanBu_SendMsg *sigleton = nil;

+ (BanBu_SendMsg *)shareInstance
{
    if(sigleton == nil)
    {
        @synchronized(self)
        {
            sigleton = [[self alloc] init];
            [sigleton initRaysource];
        }
    }
    return sigleton;
}

-(void)initRaysource
{
    
}

-(void)dealloc
{
    [super dealloc];
    
}
//限制当前对象创建多实例
#pragma mark - sengleton setting
+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (sigleton == nil)
        {
            sigleton = [super allocWithZone:zone];
        }
    }
    return sigleton;
}
+ (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)retain
{
    return self;
}


#pragma mark - 发送消息
//检查是不是VIP或好友
-(BOOL)VIPCheck
{
    BOOL bl = [MyAppDataManager judgeRelationship:MyAppDataManager.chatuid];
    
    if (bl)//是好友
    {
        return YES;
    }
    else//不是好友
    {
        //检查自己是不是VIP用户
        bl = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"userlevel"] boolValue];
        
        if (bl)
        {
            return YES;
        }
        else//双方不是好友，自己也不是VIP时跳转到申请VIP界面
        {
            [[BanBu_VIPAlert shareInstance] GoVIPApplyViewAlertFor:_appChatController title:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"vipCanUse", nil)];
        }
    }
    
    return NO;
}

#pragma mark - 发送消息并保存到数据库07/29
- (void)sendOneMsg:(id)MsgData type:(ChatCellType)type filePathExtension:(NSString *)pathExtension From:(NSString *)from
{
    //from(pb:破冰语 ty:涂鸦 mo:默认)
    //封装消息，并返回
    NSMutableDictionary * amsg = [self packagingMessage:MsgData type:type filePathExtension:pathExtension From:from];
    NSLog(@"封装好的自己的消息:%@",amsg);
    NSData * thumbnailData = nil;
    
    //保存文件
    if (type == ChatCellTypeVideo)
    {
        NSString * videoName = [AppComManager pathForVideoAlbumMedia:[NSString stringWithFormat:@"%@",[amsg valueForKey:KeyContent]]];
        
        MsgData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.mp4",videoName]];
        thumbnailData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
        
        NSString * cacheFile = [AppComManager pathForVideoMsgMedia:[amsg valueForKey:KeyContent]];
        
        [FileManager copyItemAtPath:[NSString stringWithFormat:@"%@.mp4",videoName] toPath:[NSString stringWithFormat:@"%@.mp4",cacheFile] error:nil];
        [thumbnailData writeToFile:[NSString stringWithFormat:@"%@.jpg",cacheFile] atomically:YES];
    }
    
    if((type== ChatCellTypeImage || type==ChatCellTypeVoice) && ([from isEqualToString:@"mo"] || [from isEqualToString:@"ty"] ||[from isEqualToString:@"snap"]))
    {
        NSString *savePath = [AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]];
        
        NSMutableData *data=[[NSMutableData alloc]init];
        [data appendData:MsgData];
        
        //2014年11月07日16:38:34 by yinlinlin 修改发送失败之后在发送图片显示上一张图片的问题
        [FileManager removeItemAtPath:savePath error:nil];
        //缓存发送的涂鸦、图片
        [FileManager createFileAtPath:savePath contents:data attributes:nil];
        
        [data release];
//        if(![FileManager fileExistsAtPath:savePath])
//        {
//            NSMutableData *data=[[NSMutableData alloc]init];
//            [data appendData:MsgData];
//            
//            //缓存发送的涂鸦、图片
//            [FileManager createFileAtPath:savePath contents:data attributes:nil];
//            
//            [data release];
//        }
    }
    
    if ([amsg valueForKey:KeyChatid] == nil)
    {
        NSString *chatid = [MyAppDataManager searchMaxChatid:MyAppDataManager.chatuid];
        [amsg setValue:chatid forKey:KeyChatid];
    }
    
    //更新数据源，更新界面插入到uitableview 里面去
    [_appChatController performSelectorOnMainThread:@selector(insertInToTableByMySelf:) withObject:@[amsg] waitUntilDone:YES];
    
    //保存消息到数据库中并返回saysDic和chatid
    NSDictionary * msgDic = [self saveMessageToDB:amsg];
    
    //判断好友类型，消息类型
    if (type != ChatCellTypeText)
    {
        if (![self judgeRelationship:MyAppDataManager.chatuid])
        {
            return;
        }
    }
    
    //发送消息
    [self sendMsg:MsgData thumbnailData:thumbnailData filePathExtension:pathExtension chatID:[msgDic valueForKey:KeyChatid] saysDic:[msgDic valueForKey:KeySays]];
    
    //播放发送声音5
    [self createMusic];
}

//播放发送声音
-(void)createMusic
{
    MyAppDataManager.sendMsgMusicName = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"sendMsgBoolKey"] ;
    if (!MyAppDataManager.sendMsgMusicName.length)
    {
        return;
    }
    NSString * path = [[NSBundle mainBundle]pathForResource:MyAppDataManager.sendMsgMusicName ofType:@"mp3"];
    
    if(self.audioPlayer)
    {
        [_audioPlayer release];
        _audioPlayer=nil;
    }
    
    NSError *musicError;
    self.audioPlayer=[[[AVAudioPlayer alloc]initWithData:[NSData dataWithContentsOfFile:path] error:&musicError] autorelease];
    [self.audioPlayer prepareToPlay];
    self.audioPlayer.volume=1.0;
    [self.audioPlayer play];
}

//重新发送
- (void)ReconnectOneMsg:(id)MsgData amsg:(NSMutableDictionary *)dictionary
{
    [AppComManager cancalHandlesForObject:MyAppDataManager];
    [AppComManager.networkQueue cancelAllOperations];
    
    NSMutableDictionary * diction = [NSMutableDictionary dictionaryWithDictionary:dictionary];
    
    NSArray *mapArr = typeArrDefine;
    
    NSMutableDictionary *saysDic = [NSMutableDictionary dictionaryWithCapacity:5];
    [saysDic setObject:VALUE(KeyContent, diction) forKey:KeyContent];
    [saysDic setValue:[mapArr objectAtIndex:[[diction valueForKey:KeyType] intValue]] forKey:KeyType];
    [saysDic setValue:[diction valueForKey:KeyShowFrom] forKey:KeyShowFrom];
    [saysDic setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:KeyBubbleID];
    [saysDic setValue:[diction valueForKey:KeyContent] forKey:KeyThumbnail];
    [saysDic setValue:[diction valueForKey:KeyEffectiveTime] forKey:KeyEffectiveTime];
    
    NSInteger type = [[diction valueForKey:KeyType] intValue];
    NSString * from = [diction valueForKey:KeyShowFrom];
    
    if (type == ChatCellTypeVideo)
    {
        [self copyVideoFile:[diction valueForKey:@"backupsContent"]];
        [diction setValue:[diction valueForKey:@"backupsContent"] forKey:KeyContent];
        [diction setValue:[diction valueForKey:@"backupsContent"] forKey:KeyThumbnail];
        
        [saysDic setObject:VALUE(KeyContent, diction) forKey:KeyContent];
        [saysDic setValue:[diction valueForKey:KeyThumbnail] forKey:KeyThumbnail];
    }
    
    //写聊天记录表,更新聊天记录表中该消息的发送状态发“发送中”，查找对话表中该用户的最后一条信息是否为本次发送的信息，如果是则状态改为发送中
    [MyAppDataManager updateDialogStateByReSend:[NSDictionary dictionaryWithObjectsAndKeys:MyAppDataManager.chatuid,KeyFromUid,[diction valueForKey:KeyChatid],KeyChatid, nil]];
    
    [diction setValue:[NSNumber numberWithInt:ChatStatusSending] forKey:KeyStatus];
    
    //重新获取发送时间
    NSArray * stimeArr = [self getStime];
    BOOL showStime = [[stimeArr objectAtIndex:1] boolValue];
    CGFloat height = [[diction valueForKey:KeyHeight] floatValue];
    if (_rowt == MyAppDataManager.dialogs.count-1)
    {//最后一行时都要显示时间呢，
        showStime = YES;//默认最后一条消息重发显示时间
    }
    
    if (showStime)
    {
        if (![[diction valueForKey:KeyShowtime] boolValue])
        {
            height += TimeLabelHeight;
            [diction setValue:[NSNumber numberWithFloat:height] forKey:KeyHeight];
        }
    }
    else
    {
        if ([[diction valueForKey:KeyShowtime] boolValue])
        {
            height -= TimeLabelHeight;
            [diction setValue:[NSNumber numberWithFloat:height] forKey:KeyHeight];
        }
    }
    
    [diction setValue:[stimeArr objectAtIndex:0] forKey:KeyStime];
    [diction setValue:[NSNumber numberWithBool:showStime] forKey:KeyShowtime];
    [diction setValue:[stimeArr objectAtIndex:2] forKey:KeyStimeIndex];
    
    [MyAppDataManager.dialogs removeObjectAtIndex:_rowt];
    [MyAppDataManager.dialogs addObject:diction];

    //修改本消息的发送时间，高度等信息
    [MyAppDataManager updateStime:diction];
    
    [_appChatController.tableView beginUpdates];
    NSIndexPath * firstIndexPath = [MyAppDataManager.cellRowMapDic valueForKey:[NSString stringWithFormat:@"%d",_rowt]];
    NSIndexPath * toIndexPath = [MyAppDataManager.cellRowMapDic valueForKey:[NSString stringWithFormat:@"%d",MyAppDataManager.dialogs.count-1]];
    
    [_appChatController.tableView moveRowAtIndexPath:firstIndexPath toIndexPath:toIndexPath];
    [_appChatController.tableView endUpdates];
    
    NSString *pathExtension = nil;
    if([VALUE(KeyContent, diction)hasSuffix:@"jpg"])
    {
        pathExtension = @"jpg";
    }
    else if([VALUE(KeyContent, diction)hasSuffix:@"amr"])
    {
        pathExtension = @"amr";
    }
    else if(type == ChatCellTypeVideo)
    {
        pathExtension = @"mp4";
    }
    //判断好友类型，消息类型
    if (type != ChatCellTypeText)
    {
        if (![self judgeRelationship:MyAppDataManager.chatuid])
        {
            return;
        }
    }
    
    NSData * thumbnailData = nil;
    
    if (type == ChatCellTypeVideo)
    {
        NSString * videoName = [AppComManager pathForVideoMsgMedia:[NSString stringWithFormat:@"%@",[diction valueForKey:KeyContent]]];
        MsgData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.mp4",videoName]];
        
        thumbnailData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
    }
    else if ((type == ChatCellTypeImage || type == ChatCellTypeVoice)&& ([from isEqualToString:@"mo"] || [from isEqualToString:@"ty"]))
    {
        MsgData=[NSData dataWithContentsOfFile:[AppComManager pathForMsgMedia:VALUE(KeyContent, diction)]];
    }
    
    //重新发送消息
    [self sendMsg:MsgData thumbnailData:thumbnailData filePathExtension:pathExtension chatID:[diction valueForKey:KeyChatid] saysDic:saysDic];
}

-(void)copyVideoFile:(NSString *)content
{
    //相册路径
    NSString * videoName = [AppComManager pathForVideoAlbumMedia:[NSString stringWithFormat:@"%@",content]];
    
    NSData * MsgData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.mp4",videoName]];
    
    NSData * thumbnailData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
    
    //消息缓存
    NSString * cacheFile = [AppComManager pathForVideoMsgMedia:content];
    
    [MsgData writeToFile:[NSString stringWithFormat:@"%@.mp4",cacheFile] atomically:YES];
    [thumbnailData writeToFile:[NSString stringWithFormat:@"%@.jpg",cacheFile] atomically:YES];
    
}

//判断好友关系，YES：好友；NO：非好友,暂时服务器控制，前端非好友可以发图片、视频
-(BOOL)judgeRelationship:(NSString*)userid
{
    NSString *friendIDList = [[[NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]] valueForKey:FriendShip] valueForKey:@"h"];
    friendIDList = [NSString stringWithFormat:@",%@,",friendIDList];
    if ([friendIDList rangeOfString:[NSString stringWithFormat:@",%@,",userid]].location != NSNotFound)
    {
        return YES;
    }
    
    return YES;
}

//是否在黑名单，YES：在黑名单里；NO：不在
-(BOOL)judgeRelationships:(NSString*)userid
{
    NSString *blackIDList = [[[NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]] valueForKey:FriendShip] valueForKey:@"x"];
    
    blackIDList = [NSString stringWithFormat:@",%@,",blackIDList];
    
    if ([blackIDList rangeOfString:[NSString stringWithFormat:@",%@,",userid]].location != NSNotFound)
    {
        return YES;
    }
    
    return NO;
}

//设置消息发送时间，并获取是否显示时间的BOOL值
-(NSArray *)getStime
{
    //设置发送时间
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    
    //设置showtime
    //检查是否显示时间
    BOOL showTime = YES;
    double timeInterval = 0;
    
    NSDate * date = [MyAppDataManager getLastShowTime:MyAppDataManager.chatuid];
    timeInterval = [date timeIntervalSinceDate:[formatter dateFromString:stime]];
    
    if (fabs(timeInterval) > 90)
    {
        showTime = YES;
    }
    else
    {
        showTime = NO;
    }
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *stimeIndex = [formatter stringFromDate:[NSDate date]];
    
    return @[stime,[NSNumber numberWithBool:showTime],stimeIndex];
}

//将消息封装完整并返回
-(NSMutableDictionary *)packagingMessage:(id)MsgData type:(ChatCellType)type filePathExtension:(NSString *)pathExtension From:(NSString *)from
{
    //from(pb:破冰语 ty:涂鸦 mo:默认)
    NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithCapacity:12];
    
    //获取最大的chatid，没有就默认生成一个
    NSString *chatid = [MyAppDataManager searchMaxChatid:MyAppDataManager.chatuid];
    
    //设置基本信息
    [amsg setValue:chatid forKey:KeyChatid];
    [amsg setValue:[NSNumber numberWithBool:YES] forKey:KeyMe];
    [amsg setValue:[NSNumber numberWithInt:ChatStatusSending] forKey:KeyStatus];
    [amsg setValue:[NSNumber numberWithInt:type] forKey:KeyType];
    [amsg setValue:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"uface"] forKey:KeyUface];
    [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
    
    if ([pathExtension isEqualToString:@"wav"] && [from isEqualToString:@"collect"])
    {
        [amsg setValue:@"mo" forKey:KeyShowFrom];
    }
    else
    {
        [amsg setValue:from forKey:KeyShowFrom];
    }
    
    
    [amsg setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:KeyBubbleID];
    
    NSString * dmeter = [MyAppDataManager getDmeter:MyAppDataManager.chatuid];
    [amsg setValue:dmeter forKey:KeyDmeter];
    
    //设置发送时间
    NSArray * stimeArr = [self getStime];
    BOOL showTime = [[stimeArr objectAtIndex:1] boolValue];
    
    [amsg setValue:[stimeArr objectAtIndex:0] forKey:KeyStime];
    [amsg setValue:[stimeArr objectAtIndex:1] forKey:KeyShowtime];
    
    //设置高度、内容、KeyMediaStatus
    switch (type)
    {
        case ChatCellTypeText:
        {
            [amsg setValue:MsgData forKey:KeyContent];
            if(!pathExtension)
            {
                if([from isEqual:@"mo"])
                {
                    //  cell 的高度有点小 加大一点
                    [amsg setValue:[NSNumber numberWithFloat:[BanBu_SmileLabel heightForText:MsgData]+2*CellMarge+(showTime?TimeLabelHeight:0)]forKey:KeyHeight];
                }
                else if ([from isEqualToString:@"snap"])
                {
                    [amsg setValue:[NSNumber numberWithFloat:[BanBu_SmileLabel heightForText:MsgData]+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
                    [amsg setValue:[NSNumber numberWithInt:self.textEffectiveTime] forKey:KeyEffectiveTime];
                }

                else
                {
                    [amsg setValue:[NSNumber numberWithFloat:[BanBu_SmileLabel heightForText:MsgData]+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
                }
            }
            break;
        }
        case ChatCellTypeImage:
        {
            NSString *fileName;
            //破冰语多了一个来源的高度
            if([from isEqual:@"mo"])
            {
                fileName = [NSString stringWithFormat:@"%i-%@.%@",MyAppDataManager.dialogs.count,MyAppDataManager.chatuid,pathExtension];
                [amsg setValue:fileName forKey:KeyContent];
                
                [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
                
                [amsg setValue:[NSNumber numberWithFloat:[MyAppDataManager setHeight:MsgData]+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
            }
            else
            {
                if([from isEqualToString:@"ty"])
                {
                    fileName = [NSString stringWithFormat:@"%i-%@.%@",MyAppDataManager.dialogs.count,MyAppDataManager.chatuid,pathExtension];
                    [amsg setValue:fileName forKey:KeyContent];
                    
                    [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
                    [amsg setValue:[NSNumber numberWithFloat:ImageTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
                }
                else if ([from isEqualToString:@"snap"])
                {
                    fileName = [NSString stringWithFormat:@"%i-%@.%@",MyAppDataManager.dialogs.count,MyAppDataManager.chatuid,pathExtension];
                    [amsg setValue:fileName forKey:KeyContent];
                    
                    [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
                    
                    [amsg setValue:[NSNumber numberWithFloat:[MyAppDataManager setHeight:MsgData]+2*CellMarge+(showTime?TimeLabelHeight:0) + 5] forKey:KeyHeight];
                    [amsg setValue:[NSNumber numberWithInt:self.effectiveTime] forKey:KeyEffectiveTime];
                }
                else if ([from isEqualToString:@"collectimage"])
                {
                    [amsg setValue:MsgData forKey:KeyContent];
                    
                    NSData * data = UIImageJPEGRepresentation([self getImage:amsg],1);
                    [amsg setValue:[NSNumber numberWithFloat:[MyAppDataManager setHeight:data]+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
                }
                else//破冰语、魔法工具箱
                {
                    [amsg setValue:MsgData forKey:KeyContent];
                    
//                    NSData * data =UIImageJPEGRepresentation([MyAppDataManager msgImageForImageUrlStr:[amsg valueForKey:KeyContent]], 1) ;
                    NSData * data = UIImageJPEGRepresentation([self getImage:amsg],1);
                    NSLog(@"消息的高度:%f",[MyAppDataManager setHeight:data]);
                    [amsg setValue:[NSNumber numberWithFloat:[MyAppDataManager setHeight:data]+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
                }
            }
            break;
        }
        case ChatCellTypeLocation:
        {
            // 构造发送的地址字符串经纬度：longitude：经度，latitude：纬度
            NSString *string=[NSString stringWithFormat:@"%0.f,%0.f",AppLocationManager.curLocation.longitude*1000000,AppLocationManager.curLocation.latitude*1000000];
            [amsg setValue:string forKey:KeyContent];
            [amsg setValue:[NSNumber numberWithFloat:locationTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
            break;
        }
        case ChatCellTypeVoice:
        {
            NSString *fileName;
            if([from isEqual:@"mo"])
            {
                fileName = [NSString stringWithFormat:@"%i-%@.%@",MyAppDataManager.dialogs.count,MyAppDataManager.chatuid,pathExtension];
                [amsg setValue:fileName forKey:KeyContent];
                [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
                [amsg setValue:[NSNumber numberWithFloat:VoiceTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
            }
            else if([from isEqualToString:@"collect"])
            {
                [amsg setValue:MsgData forKey:KeyContent];
                [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
                [amsg setValue:[NSNumber numberWithFloat:VoiceTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
            }
            else
            {
                [amsg setValue:MsgData forKey:KeyContent];
                
                [amsg setValue:[NSNumber numberWithFloat:VoiceTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
            }
            break;
        }
        case ChatCellTypeEmi:
        {
            [amsg setValue:MsgData forKey:KeyContent];
            [amsg setValue:[NSNumber numberWithFloat:ImageTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)] forKey:KeyHeight];
            break;
        }
        case ChatCellTypeVideo:
        {
            CGFloat fromHeight = 0;
            if ([from isEqualToString:@"snap"])
            {
                [amsg setValue:[NSNumber numberWithInt:10] forKey:KeyEffectiveTime];
                fromHeight = FromLabelHeight;
            }
            [amsg setValue:MsgData forKey:KeyContent];
            [amsg setValue:MsgData forKey:KeyThumbnail];
            [amsg setValue:MsgData forKey:@"backupsContent"];//备份视频、缩略图的名字（去掉后缀，以备重发时使用）
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
            [amsg setValue:[NSNumber numberWithFloat:VideoTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0) + fromHeight] forKey:KeyHeight];
            break;
        }
        case ChatCellTypeSpecialText:
        {
            //发送名片
            if ([from isEqualToString:@"visitCard"])
            {
                NSDictionary * sendDic = [NSDictionary dictionaryWithDictionary:MsgData];
                NSString * uface = [sendDic valueForKey:KeyUface];
                NSString * pname = [sendDic valueForKey:KeyPname];
                NSString * userid = [sendDic valueForKey:KeyFromUid];
                NSString * visitCard = NSLocalizedString(@"visitingCard", nil);
                NSString * content = kVisitCard(visitCard,uface, pname,userid);
                NSString * linkto = [sendDic valueForKey:KeyLinkTo];
                
                [amsg setValue:linkto forKey:KeyLinkTo];
                [amsg setValue:content forKey:KeyContent];
                [amsg setValue:[NSNumber numberWithFloat:2*CellMarge+(showTime?TimeLabelHeight:0)]forKey:KeyHeight];
            }
            else if ([from isEqualToString:@"magicWords"])
            {
                NSDictionary * sendDic = [NSDictionary dictionaryWithDictionary:amsg];

                NSString * content = [sendDic valueForKey:KeyContent];
                NSString * linkto = [sendDic valueForKey:KeyLinkTo];
                
                [amsg setValue:linkto forKey:KeyLinkTo];
                [amsg setValue:content forKey:KeyContent];
              //  [amsg setValue:[NSNumber numberWithFloat:2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight]forKey:KeyHeight];
                NSUserDefaults * defa=[NSUserDefaults standardUserDefaults];
                NSString * height=[defa objectForKey:KeyHeight] ;
                [amsg setValue:height forKey:KeyHeight];
                [amsg setValue:MsgData forKey:KeyContent];

            }
            
            break;
        }
        case ChatCellTypeFullScreenGif:
        {
            [amsg setValue:MsgData forKey:KeyContent];
            
            NSString * smallGifUrl = MsgData;
            smallGifUrl = [smallGifUrl substringToIndex:smallGifUrl.length-4];
            
            [amsg setValue:[NSString stringWithFormat:@"%@.jpg",smallGifUrl] forKey:KeyThumbnail];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusUpload] forKey:KeyMediaStatus];
            [amsg setValue:[NSNumber numberWithFloat:FullScreenTypeHeight+2*CellMarge+(showTime?TimeLabelHeight:0)+FromLabelHeight] forKey:KeyHeight];
            break;
        }
            
        default:
            break;
    }
    
    return amsg;
}

#pragma mark - 获取图片
-(UIImage *)getImage:(NSDictionary *)amsg
{
    UIImage * image = nil;//内容是图片时，content为图片的路径
    NSString * imagePath = nil;
    NSString * from= [amsg valueForKeyPath:KeyShowFrom];
    NSString * content = [amsg valueForKeyPath:KeyContent];
    
    if (!image && [from isEqualToString:@"store"])//这是表情商店的表情
    {
        NSArray * arr = [content pathComponents];
        NSString * imageName = [content lastPathComponent];
        NSString * folderName = [arr objectAtIndex:arr.count-2];
        
        imagePath = [AppComManager pathForEmo:imageName withFolder:folderName];
        image = [UIImage imageWithContentsOfFile:imagePath];
        
        if (![FileManager fileExistsAtPath:imagePath])
        {
            //网络路径
            [AppComManager getEmoImage:content withImageName:imageName withFolder:folderName delegate:MyAppDataManager withImageView:nil];
        }
    }
    else if (!image && [from isEqualToString:@"collect"])//收藏的表情
    {
        NSString * imagePath = [AppComManager pathForCollect:content];
        image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else if (!image && [from isEqualToString:@"collectimage"])//收藏的图片
    {
        NSString * imagePath = [AppComManager pathForCollectImage:content];
        image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else if(content.length)
    {
        image = [MyAppDataManager msgImageForImageUrlStr:content];
        if (![FileManager fileExistsAtPath:imagePath])
        {
            [AppComManager getBanBuMedia:VALUE(KeyContent, amsg) forMsgID:VALUE(KeyChatid, amsg) fromUid:MyAppDataManager.chatuid delegate:MyAppDataManager];
        }
    }
    return image;
}

//将消息保存到数据库中并返回saysDic
-(NSDictionary *)saveMessageToDB:(NSDictionary *)amsg
{
    // 把聊天记录插入到数据库当中去
    NSArray *mapArr = typeArrDefine;
    
    NSInteger type = [[amsg valueForKey:KeyType] integerValue];
    NSString * from = [amsg valueForKey:KeyShowFrom];
    
    NSMutableDictionary *saysDic = [NSMutableDictionary dictionaryWithCapacity:5];
    
    if ([[amsg valueForKey:KeyShowFrom] isEqualToString:@"snap"])
    {
        [saysDic setValue:NSLocalizedString(@"snapText", nil) forKey:KeyContent];
    }
    else if (type == ChatCellTypeSpecialText)
    {
        [saysDic setValue:NSLocalizedString(@"specialText", nil) forKey:KeyContent];
    }
    else
    {
        [saysDic setValue:VALUE(KeyContent, amsg) forKey:KeyContent];
    }
    
    [saysDic setValue:[mapArr objectAtIndex:type] forKey:KeyType];
    [saysDic setValue:from forKey:KeyShowFrom];
    [saysDic setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:KeyBubbleID];
    [saysDic setValue:VALUE(KeyEffectiveTime, amsg) forKey:KeyEffectiveTime];
    
    //消息类型是视频时，添加缩略图字段
    if (type == ChatCellTypeVideo)
    {
        [saysDic setValue:VALUE(KeyContent, amsg) forKey:KeyThumbnail];
    }
    else if(type == ChatCellTypeFullScreenGif)
    {
        [saysDic setValue:VALUE(KeyThumbnail, amsg) forKey:KeyThumbnail];
    }
    
    //在初始化
    NSString *jsonValue = [[CJSONSerializer serializer] serializeDictionary:saysDic];
    
    jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //将一条信息包到一个msglist数组去，然后同这个人的资料包到人组中去。(两种情况的个人资料不同：1、直接发起对话；2、全局接受消息得到的个人资料)
    NSMutableDictionary *peopleDic = [NSMutableDictionary dictionaryWithDictionary:_appChatController.profile];
    
    //将数据写入表(对话列表和聊天记录表)内，如果talkpeople1127表内没有这个人，就创建，否则更新（因为不会有新的个人资料，只需局部更新）。
    //写对话列表中的该人
    [peopleDic setValue:jsonValue forKey:@"says"];
    
    NSString * chatid = [amsg valueForKey:KeyChatid];
    if (chatid==nil)
    {
        chatid = [MyAppDataManager searchMaxChatid:MyAppDataManager.chatuid];
    }
    
    NSDictionary *amsg1 = [NSDictionary dictionaryWithObjectsAndKeys:jsonValue,KeySays,chatid,KeyChatid,[amsg valueForKey:KeyStime],KeyStime,MyAppDataManager.useruid,KeyFromUid, nil];
    
    NSArray *msgListArr = [NSArray arrayWithObject:amsg1];
    [peopleDic setValue:msgListArr forKey:@"msglist"];
    [peopleDic setValue:[NSNumber numberWithBool:YES] forKey:KeyMe];
    [peopleDic setValue:[NSNumber numberWithInteger:ChatStatusSending] forKey:KeyStatus];
    
    if ([MyAppDataManager initTalkPeopleOne:peopleDic withEffectiveNum:0])
    {
        MyAppDataManager.totalLoadedPeopleNum +=1;
    }
    else
    {
        [MyAppDataManager writeToTalkPeopleOne:peopleDic withEffectiveNum:0 withLevel:@"0"];
        
        if ([_appChatController.returnBtTitle isEqualToString:@"sayHi"] && _appChatController.firstSayHi)
        {
            //如果是给第一条打招呼回复的，则回复后，要修改打招呼显示的最后一条信息
            if (MyAppDataManager.secondaryTalkPeople.count>1)
            {
                [MyAppDataManager setLastDialogBySayHi:[MyAppDataManager.secondaryTalkPeople objectAtIndex:1]];
            }
            else
            {
                [MyAppDataManager deleteBlackDialog:@"600"];
                
                [MyAppDataManager.secondaryTalkPeople removeAllObjects];
                _appChatController.returnBtTitle = @"dialogueTitle";
                [_appChatController createBackButton];
            }
        }
    }
    
    //聊天详情表的数据入库
    [saysDic setValue:[amsg valueForKey:KeyContent] forKey:KeyContent];
    [saysDic setValue:[amsg valueForKey:KeyLinkTo] forKey:KeyLinkTo];
    
    jsonValue = [[CJSONSerializer serializer] serializeDictionary:saysDic];
    jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    amsg1 = [NSDictionary dictionaryWithObjectsAndKeys:jsonValue,KeySays,chatid,KeyChatid,[amsg valueForKey:KeyStime],KeyStime,MyAppDataManager.useruid,KeyFromUid,[NSNumber numberWithBool:YES],KeyMe, nil];
    
    //写聊天记录表
    [MyAppDataManager writeToDetailChatTable:amsg1 andToUid:MyAppDataManager.chatuid];
    
    return [NSDictionary dictionaryWithObjectsAndKeys:saysDic,KeySays,chatid,KeyChatid, nil];
}


#pragma mark - 发送消息
//发送
-(void)sendMsg:(id)MsgData thumbnailData:(id)thumbnailData filePathExtension:(NSString *)pathExtension chatID:(NSString *)chatid saysDic:(NSDictionary *)saysDic
{
    NSArray *mapArr = typeArrDefine;
    
    NSInteger type = [mapArr indexOfObject:[saysDic valueForKey:KeyType]];
    NSString * from = [saysDic valueForKey:KeyShowFrom];
    
    if((type== ChatCellTypeImage || type==ChatCellTypeVoice) && ([from isEqualToString:@"mo"] || [from isEqualToString:@"ty"] || [from isEqualToString:@"snap"]))
    {
        // 判断是不是破冰语
        NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [sendDic setValue:pathExtension forKey:@"extname"];
        [sendDic setValue:MyAppDataManager.chatuid forKey:KeyUid];
        [sendDic setValue:chatid forKey:KeyChatid];
        [sendDic setValue:from forKey:KeyShowFrom];
        [AppComManager uploadBanBuMedia:MsgData
                              mediaName:VALUE(KeyContent, saysDic)
                                    par:sendDic
                               delegate:MyAppDataManager];
    }
    else if (type == ChatCellTypeVideo)
    {
        //传视频
        NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:0];
        
        [sendDic setValue:MyAppDataManager.chatuid forKey:KeyUid];
        [sendDic setValue:chatid forKey:KeyChatid];
        [sendDic setValue:from forKey:KeyShowFrom];
        [sendDic setValue:[saysDic valueForKey:KeyContent] forKey:KeyContent];
        //传缩略图
        [sendDic setValue:@"jpg" forKey:@"extname"];
        [sendDic setValue:@"thumbnail" forKey:@"thumbnail"];
        [AppComManager uploadBanBuMediaThumbnail:thumbnailData
                                       mediaName:[NSString stringWithFormat:@"%@.jpg",VALUE(KeyContent, saysDic)]
                                             par:sendDic
                                        delegate:MyAppDataManager];
        
        [sendDic setValue:@"" forKey:@"thumbnail"];
        [sendDic setValue:@"mp4" forKey:@"extname"];
        [AppComManager uploadBanBuMedia:MsgData
                              mediaName:[NSString stringWithFormat:@"%@.mp4",VALUE(KeyContent, saysDic)]
                                    par:sendDic
                               delegate:MyAppDataManager];
    }
    else
    {
        [MyAppDataManager sendMsg:[NSDictionary dictionaryWithObjectsAndKeys:saysDic,KeySays,chatid,KeyChatid, nil] toUid:MyAppDataManager.chatuid];
    }
}

#pragma mark - 发送： 涂鸦、破冰语、图片、视频、表情、闪光字、翻译、魔法表情、火星文
-(void)sendMsgAllType:(NSNotification *)notifi
{
    ChatCellType type = [[[notifi object] valueForKey:KeyType] integerValue];
    NSString * from = [[notifi object]valueForKey:KeyShowFrom];
    
    switch (type)
    {
        case ChatCellTypeText:
        {
            //火星文、翻译、破冰语文本，三个方法是完全相同的，所以可以合并
            [self sendText:notifi];
        }
            break;
        case ChatCellTypeImage:
        {
            if ([from isEqualToString:@"mo"])
            {//系统相册图片
                [self systemPhoto:notifi];
            }
            else if ([from isEqualToString:@"ty"])
            {//涂鸦
                [self listeningAction:notifi];
            }
            else if ([from isEqualToString:@"pb"])
            {//破冰语--图片
                [self icePic:notifi];
            }
            else if ([from isEqualToString:@"snap"])
            {//阅后即焚--图片
                [self sendSnapMsg:notifi];
            }
            else if([from isEqualToString:@"mg"])
            {//闪光字
                [self iceSpark:notifi];
            }
            else if([from isEqualToString:@"collect"])
            {//收藏的图片
                [self collectImage:notifi];
            }
        }
            break;
        case ChatCellTypeVoice:
        {
            if ([from isEqualToString:@"pb"])
            {//破冰语--语音
                [self iceVoice:notifi];
            }
            else if([from isEqualToString:@"collect"])
            {//收藏的语音
                [self collectVoice:notifi];
            }
        }
            break;
        case ChatCellTypeVideo:
        {
            if ([from isEqualToString:@"mo"])
            {
                [self sendVideo:notifi];
            }
            else if([from isEqualToString:@"snap"])
            {
                [self sendSnapMsg:notifi];
            }
        }
            break;
        case ChatCellTypeFullScreenGif:
        {
            if ([from isEqualToString:@"mg"])
            {//魔法表情
                [self sendMagicFace:notifi];
            }
        }
            break;
        case ChatCellTypeSpecialText:
        {
            if ([from isEqualToString:@"visitCard"])
            {
                [self sendVisitingCard:notifi];
            }
            //zyfzyfzyf⬇️
            //发送魔法文字
            if ([from isEqualToString:@"magicWords"]) {
                //       [self sendMagicFace:notifi];
                [self sendText:notifi];
                
            }
            //zyfzyfzyf⬆️

        }
            break;
        default:
            break;
    }
}

#pragma mark - 发送涂鸦
//涂鸦
-(void)listeningAction:(NSNotification *)notifi
{
    NSString *imagePathExtension = @"jpg";
    NSData *data = nil;
    data = UIImageJPEGRepresentation([[notifi object] objectForKey:@"tuyaImage"], 1.0);
    
    // 这是 发送图片的 类型和方法
    [self sendOneMsg:data type:ChatCellTypeImage filePathExtension:imagePathExtension From:@"ty"];
}

//破冰语：文字;魔法工具箱：翻译、火星文
-(void)sendText:(NSNotification *)notifi
{
    NSString *content = [[notifi object]valueForKey:KeyContent];
    NSString * from = [[notifi object] valueForKey:KeyShowFrom];
    if ([from isEqualToString:@"pb"])
    {
        [self sendOneMsg:content type:ChatCellTypeText filePathExtension:nil From:@"pb"];
    }
    else if ([from isEqualToString:@"mg"])
    {
        [self sendOneMsg:content type:ChatCellTypeText filePathExtension:nil From:@"mg"];
    }
    else if ([from isEqualToString:@"mo"])
    {
        [self sendOneMsg:content type:ChatCellTypeText filePathExtension:nil From:@"mo"];
    }
    //zyfzyfzyf⬇️
    else if ([from isEqualToString:@"magicWords"])
    {//魔法文字
        [self sendOneMsg:content type:ChatCellTypeSpecialText filePathExtension:nil From:@"magicWords"];
    }
    //zyfzyfzyf⬆️

}

//破冰语：图片
-(void)icePic:(NSNotification *)notifi
{
    NSString* str =[[notifi object] valueForKey:@"image"];
    NSString *gifStr=[[notifi object] valueForKey:@"filetype"];
    
    if([gifStr isEqual:@"jpg"]||[gifStr isEqual:@"png"])
    {
        [self sendOneMsg:str type:ChatCellTypeImage filePathExtension:gifStr From:@"pb"];
    }
    
    if([gifStr isEqual:@"gif"])
    {
        [self sendOneMsg:str type:ChatCellTypeImage filePathExtension:@"gif" From:@"pb"];
    }
}

//破冰语：语音
-(void)iceVoice:(NSNotification *)notifi
{
    NSString *str=[[notifi object]valueForKey:@"music"];
    [FileManager moveItemAtPath:[AppComManager pathForMedia:str] toPath:[AppComManager pathForMsgMedia:str] error:nil];
    
    [self sendOneMsg:str type:ChatCellTypeVoice filePathExtension:@"amr" From:@"pb"];
}

#pragma mark - 发送收藏的图片
-(void)collectImage:(NSNotification *)notifi
{
    NSString* str =[[notifi object] valueForKey:@"image"];
    NSString *gifStr=[[notifi object] valueForKey:@"filetype"];
    [FileManager copyItemAtPath:[AppComManager pathForMsgMedia:str] toPath:[AppComManager pathForCollectImage:str] error:nil];
    //    if([gifStr isEqual:@"jpg"]||[gifStr isEqual:@"png"])
    {
        [self sendOneMsg:str type:ChatCellTypeImage filePathExtension:gifStr From:@"collectimage"];
    }
}

//发送图片
#pragma mark - 发送系统图片
-(void)systemPhoto:(NSNotification *)notifi
{
    UIImage * image = [[notifi object] valueForKey:@"image"];
    
    NSData * msgData = UIImageJPEGRepresentation(image, 0.2);
    
    if(msgData.length > 100000)
    {
        msgData = UIImageJPEGRepresentation([UIImage imageWithData:msgData], 0.2);
    }
    
    [self sendOneMsg:msgData type:ChatCellTypeImage filePathExtension:@"jpg" From:@"mo"];
}

//发送视频
-(void)sendVideo:(NSNotification *)notifi
{
    NSString * msgData = [[notifi object]valueForKey:@"video"];
    
    [self sendOneMsg:msgData type:ChatCellTypeVideo filePathExtension:@"mp4" From:@"mo"];
}

#pragma mark - 发送闪光字
//闪光字
-(void)iceSpark:(NSNotification *)notifi
{
    NSString* str =[[notifi object] valueForKey:@"image"];
    NSString *gifStr=[[notifi object] valueForKey:@"filetype"];
    
    if([gifStr isEqual:@"gif"])
    {
        [self sendOneMsg:str type:ChatCellTypeImage filePathExtension:@"gif" From:@"mg"];
    }
}

#pragma mark - 发送魔法表情

//发送魔法表情
-(void)sendMagicFace:(NSNotification *)notifi
{
    NSString* imagePath =[[notifi object] valueForKey:@"bigGifUrl"];
    NSString *gifStr=[[notifi object] valueForKey:@"fileType"];
    
    if([gifStr isEqual:@"gif"])
    {
        [self sendOneMsg:imagePath type:ChatCellTypeFullScreenGif filePathExtension:@"gif" From:@"mg"];
    }
}

//阅后即焚
-(void)sendSnapMsg:(NSNotification *)notifi
{
    ChatCellType type = [[[notifi object] valueForKey:KeyType] integerValue];
    if(type == ChatCellTypeImage)
    {
        UIImage * image = [[notifi object] valueForKey:@"snapImage"];
        
        NSData * msgData = UIImageJPEGRepresentation(image, 0.2);
        
        if(msgData.length > 100000)
        {
            msgData = UIImageJPEGRepresentation([UIImage imageWithData:msgData], 0.2);
        }
        
        //有效时间
        self.effectiveTime = [[[notifi object]valueForKey:KeyEffectiveTime] integerValue];

        [self sendOneMsg:msgData type:ChatCellTypeImage filePathExtension:@"jpg" From:@"snap"];
    }
    else if(type == ChatCellTypeVideo)
    {
        NSString * videoPath =[[notifi object] valueForKey:@"snapVideo"];
        
        [self sendOneMsg:videoPath type:ChatCellTypeVideo filePathExtension:@"mp4" From:@"snap"];
    }
}

//发送名片
-(void)sendVisitingCard:(NSNotification *)notifi
{
    NSDictionary * sendDic = [[notifi object]valueForKey:KeyContent];
    
    [self sendOneMsg:sendDic type:ChatCellTypeSpecialText filePathExtension:nil From:@"visitCard"];
}



-(void)collectVoice:(NSNotification *)notifi
{
    NSString *str=[[notifi object]valueForKey:@"music"];
    NSString * newFilePath = [AppComManager pathForMsgMedia:str];
    NSString * oldFilePath = [AppComManager pathForCollectImage:str];
    [FileManager copyItemAtPath:oldFilePath toPath:newFilePath error:nil];
    
    [self sendOneMsg:str type:ChatCellTypeVoice filePathExtension:@"amr" From:@"collect"];
}
@end
